﻿SELECT
	[main].object_id AS [ObjectId],
	[main].[name] AS [ObjectName],
	[main].[referenced_object_id] AS [ReferencedObjectID],
	[main].[is_disabled] AS [IsDisabled],
	[main].[is_not_for_replication] AS [IsNotForReplication],
	[main].[is_not_trusted] AS [IsNotTrusted],
	[main].[delete_referential_action] AS [DeleteReferentialAction],
	[main].[delete_referential_action_desc] AS [DeleteReferentialActionDescription],
	[main].[update_referential_action] AS [UpdateReferentialAction],
	[main].[update_referential_action_desc] AS [UpdateReferentialActionDescription],
	[main].[is_system_named] AS [IsSystemNamed],
	[table1].object_id AS [ReferencingTableId],
	[table1].[name] AS [ReferencingTableName],
	[cols].[column_id] AS [ReferencingColumnId],
	[cols].[name] AS [ReferencingColumnName],
	[table2].object_id AS [ReferencedTableId],
	[table2].[name] AS [ReferencedTableName],
	[cols2].[column_id] AS [ReferencedColumnId],
	[cols2].[name] AS [ReferencedColumnName]
FROM sys.foreign_keys [main]
INNER JOIN sys.foreign_key_columns [fkcols] ON [main].object_id = [fkcols].[constraint_object_id]
INNER JOIN sys.columns [cols] ON [fkcols].[parent_object_id] = [cols].object_id AND [fkcols].[parent_column_id] = [cols].[column_id]
INNER JOIN sys.columns [cols2] ON [fkcols].[referenced_object_id] = [cols2].object_id AND [fkcols].[referenced_column_id] = [cols2].[column_id]
INNER JOIN sys.tables [table1] ON [fkcols].[parent_object_id] = [table1].object_id
INNER JOIN sys.tables [table2] ON [fkcols].[referenced_object_id] = [table2].object_id
WHERE
	1 = 1
-- [WHERECLAUSE]
ORDER BY
	[main].[referenced_object_id],
	[main].object_id,
	[fkcols].[constraint_column_id]